﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Collections.Generic;
using System.Linq;
using exsportance.Silverlight.Common.Utils;

namespace exsportance.Silverlight.Common.Helper
{
    public class RightClickHelper
    {
        #region members
        private Dictionary<UIElement, EventHandler<RightClickEventArgs>> _list = new Dictionary<UIElement, EventHandler<RightClickEventArgs>>();
        private static RightClickHelper _instance = new RightClickHelper();
        #endregion

        #region properties

        #endregion

        private RightClickHelper()
        {
            // attach event
            if (HtmlPage.IsEnabled)
                HtmlPage.Document.AttachEvent("oncontextmenu", this.onContextMenu);
        }

        private void onContextMenu(object sender, HtmlEventArgs e)
        {

            foreach (UIElement control in _list.Keys)
            {

                IEnumerable<UIElement> list = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(new Point(e.ClientX, e.ClientY), control);
                if (list.Count() > 0)
                {
                    _list[control](sender, new RightClickEventArgs() { X = e.ClientX, Y = e.ClientY, OffsetX = e.OffsetX, OffsetY = e.OffsetY });
                }

            }

            e.PreventDefault();
        }

        public static void RegisterRightClick(UIElement control, EventHandler<RightClickEventArgs> onClick)
        {
            if (!_instance._list.ContainsKey(control))
                _instance._list.Add(control, onClick);
        }

        public static void UnregisterRightClick(UIElement control)
        {
            if (_instance._list.ContainsKey(control))
                _instance._list.Remove(control);
        }
    }


    public class RightClickEventArgs : EventArgs
    {
        public int X { get; set; }
        public int Y { get; set; }

        public int OffsetX { get; set; }
        public int OffsetY { get; set; }

        public Point Location { get { return new Point(X, Y); } }
        public Point OffsetLocation { get { return new Point(OffsetX, OffsetY); } }
    }
}
